<template>
  <doc-alert title="【交易】售后退款" url="https://doc.iocoder.cn/mall/trade-aftersale/" />

  <ContentWrap>
    <div :class="searchVisible ? 'flex flex-row flex-wrap mb-2' : 'flex flex-row flex-wrap'">
      <el-button plain type="success" @click="searchVisible = !searchVisible">
        <Icon class="mr-5px" icon="ep:operation" />
        {{ searchVisible ? '关闭筛选' : '打开筛选' }}
      </el-button>
      <el-text type="info">
        <span class="ml-5px">{{ searchVisible ? '关闭以下筛选条件' : '点击打开筛选条件' }}</span>
      </el-text>
      <div class="flex-1"></div>
      <el-button @click="resetQuery">
        <Icon class="mr-5px" icon="ep:refresh" />
        刷新列表
      </el-button>
    </div>
    <el-form
      v-if="searchVisible"
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="spuName">
        <el-input
          v-model="queryParams.spuName"
          class="!w-280px"
          clearable
          placeholder="请输入产品 SPU 名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退款编号" prop="no">
        <el-input
          v-model="queryParams.no"
          class="!w-280px"
          clearable
          placeholder="请输入退款编号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          class="!w-280px"
          clearable
          placeholder="请输入订单编号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="售后状态" prop="status">
        <el-select
          v-model="queryParams.status"
          class="!w-280px"
          clearable
          placeholder="请选择售后状态"
        >
          <el-option label="全部" value="0" />
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="售后方式" prop="way">
        <el-select
          v-model="queryParams.way"
          class="!w-280px"
          clearable
          placeholder="请选择售后方式"
        >
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_WAY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="售后类型" prop="type">
        <el-select
          v-model="queryParams.type"
          class="!w-280px"
          clearable
          placeholder="请选择售后类型"
        >
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-280px"
          end-placeholder="自定义时间"
          start-placeholder="自定义时间"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-tabs v-model="queryParams.status" @tab-click="tabClick">
      <el-tab-pane
        v-for="item in statusTabs"
        :key="item.label"
        :label="item.label"
        :name="item.value"
      />
    </el-tabs>
    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column align="left" label="售后标识" min-width="250">
        <template #default="scope">
          <div class="flex flex-col">
            <p>退款单号：{{ scope.row.no }}</p>
            <p
              >交易单号：<el-button link type="primary" @click="openOrderDetail(scope.row.orderId)">
                {{ scope.row.orderNo }}
              </el-button></p
            >
            <span>申请时间：{{ formatDate(scope.row.createTime) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="产品信息" min-width="300">
        <template #default="{ row }">
          <div class="flex flex-row">
            <el-image
              :src="row.picUrl"
              class="!h-[50px] !w-[50px]"
              fit="contain"
              :preview-src-list="[row.picUrl || './placeholder.png']"
              :initial-index="0"
              :preview-teleported="true"
              :hide-on-click-modal="true"
            />
            <div class="flex flex-col items-start ml-10px">
              <el-tooltip :content="row.spuName" placement="top">
                <span class="overflow-ellipsis max-h-[50px] overflow-hidden">
                  {{ row.spuName }}
                </span>
              </el-tooltip>
              <div class="flex flex-wrap">
                <el-tag
                  v-for="property in row.properties"
                  :key="property.propertyId"
                  class="mb-[10px] mr-[10px]"
                >
                  {{ property.propertyName }}: {{ property.valueName }}
                </el-tag>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="申请信息" min-width="220">
        <template #default="scope">
          <div class="flex flex-col">
            <span>买家：{{ scope.row.user.nickname }}</span>
            <div class="flex flex-row items-baseline">
              <span>金额：</span
              ><span class="text-red-500 mr-2px">{{ fenToYuan(scope.row.refundPrice) }}</span
              ><span>元</span>
            </div>
            <el-tooltip
              :content="scope.row.applyDescription || scope.row.applyReason"
              placement="top"
            >
              <span>理由：{{ scope.row.applyReason }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="100">
        <template #default="scope">
          <div>
            <dict-tag :type="DICT_TYPE.TRADE_AFTER_SALE_STATUS" :value="scope.row.status" />
            <dict-tag :type="DICT_TYPE.TRADE_AFTER_SALE_WAY" :value="scope.row.way" />
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="160">
        <template #default="{ row }">
          <el-button link type="warning" @click="openAfterSaleDetail(row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
</template>
<script lang="ts" setup>
import * as AfterSaleApi from '@/api/mall/trade/afterSale/index'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { TabsPaneContext } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { fenToYuan } from '@/utils'

defineOptions({ name: 'TradeAfterSale' })

const { push } = useRouter() // 路由跳转

const searchVisible = ref(false) // 搜索表单是否可见
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<AfterSaleApi.TradeAfterSaleVO[]>([]) // 列表的数据
const statusTabs = ref([
  {
    label: '全部',
    value: ''
  }
])
const queryFormRef = ref() // 搜索的表单
// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: null,
  status: '',
  orderNo: null,
  spuName: null,
  createTime: [],
  way: null,
  type: null
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = cloneDeep(queryParams)
    const res = await AfterSaleApi.getAfterSalePage(data)
    list.value = res.list as AfterSaleApi.TradeAfterSaleVO[]
    total.value = res.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNo = 1
  await getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** tab 切换 */
const tabClick = async (tab: TabsPaneContext) => {
  queryParams.status = tab.paneName as string
  await getList()
}

/** 查看售后详情 */
const openAfterSaleDetail = (id: number | string) => {
  push({ name: 'TradeAfterSaleDetail', params: { id } })
}

/** 查看订单详情 */
const openOrderDetail = (id: number | string) => {
  push({ name: 'TradeOrderDetail', params: { id } })
}

onMounted(async () => {
  await getList()
  // 设置 statuses 过滤
  for (const dict of getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_STATUS)) {
    statusTabs.value.push({
      label: dict.label,
      value: dict.value
    })
  }
})
</script>
